package com.lzh.seatrend.service.impl;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.lzh.seatrend.common.Result;
import com.lzh.seatrend.common.constant.ResultCode;
import com.lzh.seatrend.controller.sms.SmsController;
import com.lzh.seatrend.service.SmsService;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * ctrl + alt + 7 查看方法的调用链
 * @Classname SmsServiceImpl
 * @Description TODO
 * @Date 2021/11/15 11:35
 * @Created by liuzihao
 */
@Service
public class SmsServiceImpl implements SmsService {

    private final Logger logger = LoggerFactory.getLogger(SmsController.class);

    @Value("${qcloudsms.appId}")
    private int appId;

    @Value("${qcloudsms.appKey}")
    private String appKey;

    /**
     * 短信模板id，需要在短信应用中申请
     */
    private int templateId = 1413;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 过期时间
     */
    private long phoneExpire = 2;

    private int SAVE = 1;
    private int NOT_SAVE = 0;

    /**
     * @Description 生成随机4位数
     * @Param null
     * @return java.lang.String
     * @date 2021/11/15 11:45
     * @auther liuzihao
     */
    public static String getRandom(){
        Random random = new Random();
        StringBuffer randomSb = new StringBuffer();
        for (int i = 0, a; i < 4; i++) {
            a = random.nextInt(10);
            randomSb.append(a);
        }
        return randomSb.toString();
    }

//    public static void main(String[] args) {
//        System.out.println(getRandom());
//    }

    @Override
    public Result sendMessageWithTemplate(String phone) {
        Result result = new Result();
        try {
            String[] params = new String[1];
            params[0] = getRandom();
            SmsSingleSender smsSingleSender = new SmsSingleSender(appId,appKey);
            //签名参数未提供或者为空时，会使用默认签名发送短信
            /**
             * 指定模板单发
             *
             * @param nationCode 国家码，如 86 为中国
             * @param phoneNumber 不带国家码的手机号
             * @param templateId 信息内容
             * @param params 模板参数列表，如模板 {1}...{2}...{3}，那么需要带三个参数 （验证码）
             * @param sign 签名，如果填空，系统会使用默认签名
             * @param extend 扩展码，可填空
             * @param ext 服务端原样返回的参数，可填空
             * @return {@link}SmsSingleSenderResult
             * @throws HTTPException  http status exception
             * @throws JSONException  json parse exception
             * @throws IOException    network problem
             */
            SmsSingleSenderResult smsSingleSenderResult = smsSingleSender.sendWithParam("86",phone,templateId,params,
                    "测试发送-这是标签","","");
            logger.info(smsSingleSender.toString());
            if (smsSingleSenderResult.result == 0){
                int isSave = saveCodeToRedis(phone, params[0]);
                return isSave == SAVE ? result.setMsg(ResultCode.SUCCESS) : result.setMsg(ResultCode.FAIL);
            } else {
                return result.setMsg(ResultCode.FAIL);
            }
        } catch (HTTPException e) {
            e.printStackTrace();
            return result.setMsg(ResultCode.FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return result.setMsg(ResultCode.FAIL);
        }
    }

    @Override
    public int saveCodeToRedis(String phone, String code) {
        redisTemplate
                .opsForValue()
                .set(phone,code,phoneExpire, TimeUnit.MINUTES);
        return redisTemplate.hasKey(phone) ? SAVE : NOT_SAVE;
    }


}
